package com.ybfenpan.controller.member.member;


import com.ybfenpan.controller.core.BaseController;
import com.ybfenpan.model.Member;
import com.ybfenpan.model.ParamWage;
import com.ybfenpan.service.DailiService;
import com.ybfenpan.service.MemberService;
import com.ybfenpan.service.ParamWageService;
import com.ybfenpan.taglib.annotation.Token;
import com.ybfenpan.utils.ContextUtil;
import com.ybfenpan.utils.CryptUtil;
import com.ybfenpan.utils.MapUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ybfenpan.utils.StringUtil.isMobile;


/**
 * Created by Administrator on 2016/3/25.
 */
@Controller

public class MemberController extends BaseController {
    @Resource
    private MemberService memberService;
    @Resource
    private DailiService dailiService;

    @Resource
    private ParamWageService paramWageService;


    /**
     * 注册show
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("member/member/memberAddShow.shtml")
    public String list(HttpServletRequest request) throws Exception {

        //获取list
        Map formMap = getParameterMap(request);

        Member member = ContextUtil.getMember();
        request.setAttribute("recommendLoginName", member.getLoginName());

        List dailiList = dailiService.queryForList("select", formMap);
        request.setAttribute("dailiList", dailiList);


        //接点图传过来的参数
        String fatherLoginName = MapUtil.getString(formMap, "fatherLoginName");
        String qu = MapUtil.getString(formMap, "qu");

        request.setAttribute("qu", qu);
        request.setAttribute("fatherLoginName", fatherLoginName);

        return "member/member/memberAdd";
    }

    /**
     * 注册
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("member/member/memberAdd.shtml")
    public String add(ModelMap model, HttpServletRequest request) throws Exception {
        Map formMap = getParameterMap(request);
        Member regist = ContextUtil.getMember();
        /*****************验证******************/

        //注册人
        Member register = ContextUtil.getMember();
        boolean result = true;
        //账号
        String loginName = MapUtil.getString(formMap, "loginName");

        if (memberService.executMemberByLoginName(loginName) != null) {
            setMessage(model, "该代理商账号已经存在。");
            result = false;
        }

        if (loginName == null || "".equals(loginName)) {
            setMessage(model, "请输入代理商账号。");
            result = false;
        }

        if (!isMobile(loginName)) {
            setMessage(model, "您输入的账号不是手机号。");
            result = false;

        }

        String regEx = "[\u4e00-\u9fa5]";
        Pattern pat = Pattern.compile(regEx);
        Matcher matcher = pat.matcher(loginName);
        if (matcher.find()) {
            setMessage(model, "登录名不能包含中文。");
            result = false;

        }
        //过滤登录名的特殊字符
        if (loginName.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() != 0) {

            setMessage(model, "该登录名含有特殊字符，请重新填写！");
            result = false;
        }

        if (loginName.length() > loginName.replaceAll(" ", "").length()) {
            setMessage(model, "该登录名含有空格，请重新填写！");
            result = false;
        }


        //推荐人
        String recommendLoginName = MapUtil.getString(formMap, "recommendLoginName");

        Integer recommendId = null;
        Member recommend;
        if (recommendLoginName != null && !recommendLoginName.equals("")) {
            recommend = memberService.executMemberByLoginName(recommendLoginName);
            if (recommend != null) {
                if (recommend.getAccountActive().equals("F")) {
                    setMessage(model, "推荐人未报单。");
                    result = false;
                } else {
                    recommendId = recommend.getId();
                }
            } else {
                setMessage(model, "推荐人不存在。");
                result = false;

            }
        } else {
            setMessage(model, "请输入推荐人！");
            result = false;

        }


        String onePsw = MapUtil.getString(formMap, "onePassword");
        if (onePsw.length() < 6) {
            setMessage(model, "一级密码必须大于6位。");
            result = false;
        }


        String twoPsw = MapUtil.getString(formMap, "twoPassword");
        if (twoPsw.length() < 6) {
            setMessage(model, "二级密码必须大于6位。");
            result = false;
        }

        String personName = MapUtil.getString(formMap, "personName", "");
        if ("".equals(personName)) {
            setMessage(model, "请输入姓名！");
            result = false;
        }

        String bankPersonName = MapUtil.getString(formMap, "bankPersonName", "");
        if ("".equals(bankPersonName)) {
            setMessage(model, "请输入开户名！");
            result = false;
        }

        String bankCardNo = MapUtil.getString(formMap, "bankCardNo", "");
        if ("".equals(bankCardNo)) {
            setMessage(model, "请输入银行卡号！");
            result = false;
        }

        String bankSheng = MapUtil.getString(formMap, "bankSheng", "");
        if ("".equals(bankSheng)) {
            setMessage(model, "请输入开户行所在省！");
            result = false;
        }

        String bankShi = MapUtil.getString(formMap, "bankShi", "");
        if ("".equals(bankShi)) {
            setMessage(model, "请输入开户行所在市！");
            result = false;
        }

        String bankAddress = MapUtil.getString(formMap, "bankAddress", "");
        if ("".equals(bankAddress)) {
            setMessage(model, "请输入开户行详细地址！");
            result = false;
        }

        if (!result) {

            request.setAttribute("recommendLoginName", regist.getLoginName());
            List dailiList = dailiService.queryForList("select", formMap);
            request.setAttribute("dailiList", dailiList);
            request.setAttribute("member", formMap);
            return "member/member/memberAdd";
        }


        String onePassword = CryptUtil.getInstance().encrypt2String(onePsw, CryptUtil.keyStr);

        String twoPassword = CryptUtil.getInstance().encrypt2String(twoPsw, CryptUtil.keyStr);

//        Integer dailiId = MapUtil.getInteger(formMap, "dailiId");
//        Daili daili=this.dailiService.getByKey(dailiId);
        ParamWage paramWage1004 = this.paramWageService.getByKey(1004);
        Member one = new Member();

        one.setLoginName(loginName);
        one.setOnePassword(onePassword);
        one.setTwoPassword(twoPassword);
        one.setRecommendId(recommendId);
        one.setRegisterId(register.getId());
//        one.setDailiId(dailiId);
        one.setPayNum(paramWage1004.getValue());
//        one.setLevel(dailiId);

        one.setCardNo(MapUtil.getString(formMap, "cardNo"));
        one.setRemark(MapUtil.getString(formMap, "remark"));
        one.setTel(MapUtil.getString(formMap, "tel"));
        one.setPersonName(MapUtil.getString(formMap, "personName"));
        one.setWei(MapUtil.getString(formMap, "wei"));
        one.setQq(MapUtil.getString(formMap, "qq"));

        one.setBankShi(MapUtil.getString(formMap, "bankShi"));
        one.setBankShi(MapUtil.getString(formMap, "bankPersonName"));
        one.setBankName(MapUtil.getString(formMap, "bankName"));
        one.setBankAddress(MapUtil.getString(formMap, "bankAddress"));
        one.setBankCardNo(MapUtil.getString(formMap, "bankCardNo"));
        one.setBankSheng(MapUtil.getString(formMap, "bankSheng"));
        one.setBankPersonName(MapUtil.getString(formMap, "personName"));

        memberService.saveOne(one);

        return "redirect:memberNoActiveList.shtml";

    }

    /**
     * 注册ajax
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("member/member/ajaxGetRecommendByName.shtml")
    @ResponseBody
    public void ajaxTuRecommendAction(HttpServletRequest request, HttpServletResponse response) {

        Object retObj = null;
        Map formMap = getParameterMap(request);
        String recommendLoginName = MapUtil.getString(formMap, "recommendLoginName");
        Member member = memberService.executMemberByLoginName(recommendLoginName);
        String personName = "";
        HashMap resultformMap = new HashMap();
        if (member != null) {
            retObj = member;
            personName = member.getPersonName();
            resultformMap.put("member", member);
            resultformMap.put("personName", personName);

            renderSuccess(response, true, resultformMap);
        } else {


            renderSuccess(response, false, resultformMap);

        }

    }

    /**
     * 注册ajax
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("member/member/ajaxGetFatherByName.shtml")
    @ResponseBody
    public void ajaxTuFahterAction(HttpServletRequest request, HttpServletResponse response) {

        Object retObj = null;
        Map formMap = getParameterMap(request);
        String fatherLoginName = MapUtil.getString(formMap, "fatherLoginName");
        Member member = memberService.executMemberByLoginName(fatherLoginName);
        String personName = "";
        HashMap resultformMap = new HashMap();
        if (member != null) {
            retObj = member;
            if (member.getZuoId() != null && member.getYouId() != null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，左右区均有人，请重新填写。");
            }
            if (member.getZuoId() != null && member.getYouId() == null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，左区有人，请放在右区。");
            }
            if (member.getZuoId() == null && member.getYouId() != null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，右区有人，请放在左区。");
            }
            if (member.getZuoId() == null && member.getYouId() == null) {

                resultformMap.put("title", "姓名：" + member.getPersonName() + "，左右区都没有人。");
            }
            renderSuccess(response, true, resultformMap);
        } else {

            renderSuccess(response, false, resultformMap);

        }

    }


    /**
     * 服务中心
     *
     * @param request
     * @param response
     */
    @RequestMapping("member/member/ajaxGetCenterByName.shtml")
    @ResponseBody
    public void ajaxTuCenterAction(HttpServletRequest request, HttpServletResponse response) {

        Object retObj = null;
        Map formMap = getParameterMap(request);
        String centerLoginName = MapUtil.getString(formMap, "centerLoginName");
        Member member = memberService.executMemberByLoginName(centerLoginName);
        String personName = "";
        HashMap resultformMap = new HashMap();
        if (member != null && member.getHistoryBuyStock() > 0) {

            retObj = member;
            personName = member.getPersonName();
            resultformMap.put("member", member);
            resultformMap.put("personName", personName);
            renderSuccess(response, true, resultformMap);
        } else {

//            resultformMap.put("personName", "该代理商不是报单中心。");
            renderSuccess(response, false, resultformMap);

        }
    }

    /**
     * loginName检测  ajax
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("member/member/ajaxGetMemberByName.shtml")
    @ResponseBody
    public void ajaxGetMemberByName(HttpServletRequest request, HttpServletResponse response) {


        Map formMap = getParameterMap(request);
        String loginName = MapUtil.getString(formMap, "loginName");
        Member member = memberService.executMemberByLoginName(loginName);

        HashMap resultformMap = new HashMap();
        if (member == null) {

            renderSuccess(response, true, resultformMap);
        } else {

            renderSuccess(response, false, resultformMap);

        }

    }


    /**
     * 报单显示
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Token(save = true)
    @RequestMapping("member/member/memberActiveShow.shtml")
    public String show(HttpServletRequest request) throws Exception {
        Map formMap = getParameterMap(request);
        Member active = ContextUtil.getMember();

        active = memberService.getByKey(active.getId());


        request.setAttribute("active", active);
        List<Map<String, Object>> list = memberService.queryForList("memberForList", formMap);

        if (list.size() > 0) {

            Map<String, Object> member = list.get(0);
//            ParamWage paramWage1014 = this.paramWageService.getByKey(1014);
//            request.setAttribute("paramWage1014", paramWage1014.getValue());
            request.setAttribute("member", member);
        }
        return "member/member/memberActive";


    }

    /**
     * 报单
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("member/member/memberActive.shtml")
    @ResponseBody
    @Token(remove = true)
    public void update(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {

        Map formMap = getParameterMap(request);

        String myTwoPassword = MapUtil.getString(formMap, "myTwoPassword");
        String activeLoginName = MapUtil.getString(formMap, "activeLoginName");
        String loginName = MapUtil.getString(formMap, "loginName");
        Integer payType = MapUtil.getInteger(formMap, "activeType", 0);
        Member member = memberService.executMemberByLoginName(activeLoginName);

        boolean result = true; // 验证结果
        String msg = "";
        if (member != null) {

            // 报单人
            Member active = ContextUtil.getMember();
            active = memberService.getByKey(active.getId());
            // 要报单的代理商

            if (!member.getLoginName().equals(loginName)) {
                // setMessage(model,"代理商账号不正确。");
                msg = "代理商账号不正确。";
                result = false;
            }
            if (member.getAccountActive().equals("F")) {

                String pwd = CryptUtil.getInstance().encrypt2String(myTwoPassword, CryptUtil.keyStr);
                if (!active.getTwoPassword().equals(pwd)) {
                    // setMessage(model,"安全密码不正确。");
                    msg = "安全密码不正确。";
                    result = false;
                } else {
                    // 推荐人验证
                    if (member.getRecommendId() != null) {
                        Member recommend = memberService.getByKey(member.getRecommendId());
                        if (recommend != null) {
                            if (recommend.getAccountActive().equals("F")) {
                                msg = "推荐人未报单。";
                                result = false;
                            }
                        }

                    }

                    if (payType == 10) {
                        if (active.getMoney() < member.getPayNum()) {
                            msg = "现金积分不足：" + member.getPayNum();
                            result = false;
                        }
                    } else if (payType == 20) {
                        if (active.getEle() < member.getPayNum()) {
                            msg = "报单积分不足：" + member.getPayNum();
                            result = false;
                        }
                    }
                }

            } else {
                msg = "代理商已经报单。";
                result = false;
            }

            if (result) {
                memberService.saveActive(member.getId(), active.getId(), payType);
            }

        }
        HashMap resultformMap = new HashMap();
        resultformMap.put("msg", msg);
        renderSuccess(response, result, resultformMap);

    }
}
